import * as PIXI from 'pixi.js'
import { PixiComponent } from '@inlet/react-pixi'

function onClick(callback) {
  return (event) => {
    const position = event.data.getLocalPosition(this)
    callback(position.x, position.y)
  }
}

export default PixiComponent('Polygon', {
  create: () => new PIXI.Graphics(),
  didMount: () => { },
  willUnmount: () => { },
  applyProps: (instance, oldProps, newProps) => {
    instance.clear()
    const {
      hole,
      click,
      edit,
      label,
      color,
    } = newProps
    if (label.hide !== true || edit === true) {
      const point = label.exterior
      const lines = point.reduce((pre, next) => {
        pre.push(next[0])
        pre.push(next[1])
        return pre
      }, [])
      instance.lineStyle(0)
      instance.beginFill(parseInt(color.substring(1), 16), 0.5)
      instance.drawPolygon(lines)
      label.interior.forEach((polygonHole) => {
        polygonHole.forEach((holePoint, index) => {
          const x = holePoint[0]
          const y = holePoint[1]
          if (index === 0) {
            instance.moveTo(x, y)
          } else {
            instance.lineTo(x, y)
          }
        })
        instance
          .addHole()
          .closePath()
      })

      if (hole === true) {
        instance.interactive = true
        instance.removeAllListeners(['pointerdown'])
        instance.on('pointerdown', onClick(click))
      } else {
        instance.interactive = false
      }
    }
  },
})
